<?php
/**
 * Desc: Service模板
 * User: zdb
 * Date: 2023/6/5
 * Time: 11:22
 */

namespace app\api\service\clockin;
use app\util\CommonUtil;
use app\util\DateUtil;
use think\facade\Db;

class ClockinActivityService
{

    private $primaryTable;
    CONST ARR_CONTENT_TYPE = array('poem' => 1, 'en_vocabulary' => 2, 'movie_word_en' => 3);
    CONST ARR_ACTIVITY_STATUS = array('on_shelf' => 1, 'off_shelf' => 2, 'new' => 9, 'delete' => 0);

    public function __construct()
    {
        $this->primaryTable = "yj_clockin_activity";
    }

    public function findRowById($id)
    {
        return Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->find();
    }

    public function findRowByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        return Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->strict(false)
            ->find();
    }

    public function getListByManyId($arrId)
    {
        $list = Db::table($this->primaryTable)->alias('a')
            ->whereIn('id', $arrId)
            ->select()
            ->toArray();
        return $list;
    }

    public function assembleFilterCondition($data)
    {
        $condition = ['a.status > 0'];

        if (!empty($data['title'])) {
            $condition[] = "title like '%" . $data['title'] . "%'";
        }

        if(!empty($data['content_type'])){
            $condition[] = "a.content_type = ".$data['content_type'];
        }


        if (!empty($data['activity_name'])) {
            $condition[] = "a.activity_name like '%" . $data['activity_name'] . "%'";
        }

        return empty($condition) ? "" : implode(" AND ", $condition);
    }

    public function getListNoPage($data = [])
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->select()
            ->toArray();
        return $res;
    }

    public function getListWithPage($data, $pageIndex = 1, $pageSize = 30)
    {
        $offset = ($pageIndex - 1) * $pageSize;
        $condition = $this->assembleFilterCondition($data);
        if(self::ARR_CONTENT_TYPE['movie_word_en'] == $data['content_type']){
            $list = Db::table($this->primaryTable)->alias('a')
                ->leftJoin("yj_lib_movie b", "a.subject_id=b.id")
                ->where($condition)
                ->limit($offset, $pageSize)
                ->order('a.id desc')
                ->field("a.*, b.movie_name_cn")
                ->select()
                ->toArray();
        }else if(self::ARR_CONTENT_TYPE['poem'] == $data['content_type']){
            $list = Db::table($this->primaryTable)->alias('a')
                ->leftJoin("yj_lib_poem p", "a.subject_id=p.id")
                ->where($condition)
                ->limit($offset, $pageSize)
                ->order('a.id desc')
                ->field("a.*, p.poem_title")
                ->select()
                ->toArray();
        }

        foreach($list as &$item){
            $statusInfo = $this->getClockinActivityStatus($item);
            $item['step_status'] = $statusInfo['status_text_cn'];
        }
        return $list;
    }

    public function getTotalNum($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $num = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->count();
        return $num;
    }

    public function createRow($data)
    {
        $data['status'] = isset($data['status']) ? $data['status']:1;
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->insert($data, true);
        return $res;
    }

    public function createManyRow($data)
    {
        $res = Db::table($this->primaryTable)
            ->strict(false)
            ->duplicate($data)
            ->insertAll($data, true);
        return $res;
    }

    public function updateRowById($id, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByData($condition, $data)
    {
        $condition = $this->assembleFilterCondition($data);
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function updateListByManyId($arrId, $data)
    {
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeRowById($id)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)
            ->where('id', '=', $id)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByManyId($arrId)
    {
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->whereIn('a.id', $arrId)
            ->strict(false)
            ->save($data);
        return false !== $res ? true : false;
    }

    public function removeListByData($data)
    {
        $condition = $this->assembleFilterCondition($data);
        $data = ['status' => 0];
        $res = Db::table($this->primaryTable)->alias('a')
            ->where($condition)
            ->save($data);
        return false !== $res ? true : false;
    }

    /**
     * 获取最新10条有效活动
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getRecentList()
    {
        $limit = 10;
        $list = Db::table($this->primaryTable)->alias('a')
            ->where('a.status', '>', 0)
            ->order("a.id", "desc")
            ->limit($limit)
            ->select()
            ->toArray();
        return $list;
    }


    /**
     * 获取在线打卡活动
     * @param $contentType 1-poem 2-en vocabulary
     * @param int $userId
     * @return array
     */
    public function getOnlineClockinActivityList($contentType, int $userId = 0)
    {
        $currentDate = DateUtil::getCurrentDatetime("Y-m-d");
        if($userId){
//            $condition = $this->assembleFilterCondition($data);
//            $res = Db::table($this->primaryTable)->alias('a')
//                ->where($condition)
//                ->select()
//                ->toArray();
//            return $res;
        }else{
            $list = Db::table($this->primaryTable)->alias('a')
                ->where('a.content_type', '=', $contentType)
                ->where('a.end_time', '>=', $currentDate)
                ->where('a.status', '=', 1)
                ->select()
                ->toArray();
        }
        $serviceActivityPlanTask = new ClockinActivityPlanTaskService();
        foreach($list as &$item){
           //获取每个活动当天的计划
            $clockinActivityId = $item['id'];
            //活动
            $statusInfo = $this->getClockinActivityStatus($item, $currentDate);
            $item['status_text'] = $statusInfo['status_text'];
            $item['status_text_cn'] = $statusInfo['status_text_cn'];
            $planList = $serviceActivityPlanTask->getPoemActivityPlanByDate($clockinActivityId, $currentDate);
            $item['plan_list'] = $planList;
        }
        return $list;
    }

    /**
     * 获取打卡活动的状态
     * 新建/预热中、报名中、打卡中、已结束/下架/已删除
     * @param $info
     */
    public function getClockinActivityStatus($info, $date = '')
    {
        if(empty($date)){
            $date = DateUtil::getCurrentDatetime("Y-m-d");
        }
        if(self::ARR_ACTIVITY_STATUS['new'] == $info['status']){
            $statusText = 'new';
            $statusTextCn = '新建';
        }else if(self::ARR_ACTIVITY_STATUS['on_shelf'] == $info['status']){
            if($date < $info['join_start_time']){
                $statusText = 'preheating';
                $statusTextCn = '预热中';
            }else if($date >= $info['join_start_time'] && $date < $info['start_time']){
                $statusText = 'join';
                $statusTextCn = '报名中';
            }else if($date >= $info['start_time'] && $date <= $info['end_time']){
                $statusText = 'clockin';
                $statusTextCn = '打卡中';
            }else if($date > $info['end_time']){
                $statusText = 'end';
                $statusTextCn = '已结束';
            }
        }else if(self::ARR_ACTIVITY_STATUS['off_shelf'] == $info['status']){
            $statusText = 'off_shelf';
            $statusTextCn = '已下架';
        }else if(self::ARR_ACTIVITY_STATUS['delete'] == $info['status']){
            $statusText = 'delete';
            $statusTextCn = '已删除';
        }
        return array(
            'status_text' => $statusText,
            'status_text_cn' => $statusTextCn
        );
    }



    /**
     * Desc:
     * @param $activityInfo 非数组格式则代表是activityId
     * @param false $withPlanFlag
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Datetime: 2024/11/13 10:41 by zdb
     */
    public function getClockinActivityDateList($activityInfo, $withPlanFlag = false)
    {
        if(!is_array($activityInfo)){
            $activityInfo = $this->findRowById($activityInfo);
        }
        $startDate = $activityInfo['start_time'];
        $endDate = $activityInfo['end_time'];
        $dateList = DateUtil::getPeriodDateList($startDate, $endDate);
        $newDateList = array();
        $currentDate = DateUtil::getCurrentDatetime("Y-m-d");
        if($withPlanFlag){
            $serviceClockinActivityPlan = new ClockinActivityPlanService();
            $planList = $serviceClockinActivityPlan->getListNoPage(array('clockin_activity_id' => $activityInfo['id']));
            $planListByDate = array_column($planList, null, 'plan_date');
            $columnPlanDate = array_column($planList, 'plan_date');
            foreach($dateList as $date){
                if(in_array($date, $columnPlanDate)){
                    $planId = $planListByDate[$date]['id'];
                }else{
                    $planId = 0;
                }
                if($currentDate == $date){
                    $isCurrent = 1;
                }else{
                    $isCurrent = 0;
                }
                $newDateList[] = [
                    'date' => $date,
                    'plan_id' => $planId,
                    'is_current' => $isCurrent
                ];
            }
        }else{
            foreach($dateList as $date){
                if($currentDate == $date){
                    $isCurrent = 1;
                }else{
                    $isCurrent = 0;
                }
                $newDateList[] = [
                    'date' => $date,
                    'plan_id' => 0,
                    'is_current' => $isCurrent
                ];
            }
        }
        return $newDateList;
    }
}